import React, { Component, Fragment } from 'react';
import { Link } from 'dva/router';
import { connect } from 'dva';
import router from 'umi/router';
import { Tabs,} from 'zent';
import { Card, Table, Input, Modal, Form, Button, Spin,message} from 'antd';
import styles from './index.less';
const confirm = Modal.confirm;
@Form.create()
class Pagination extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showType: 0,
      limit: 10,
      current: 0,
      total: 0,
      maxPageToShow: 8,
      pageSize: 10,
      Type: this.props.location.pathname === `/${window.storeId}/store/pages` ? 1 : 2,
      paginationProps: {
        showSizeChanger: true,
        showQuickJumper: false,
        showTotal: total => `共 ${total} 条记录`,
        pageSize: 10,
        total: 0,
      },
      loading: true,
      visible: false,
      wxaUrl:''
    };
  }
  componentWillMount() {
    const { dispatch, form } = this.props;
    window.scrollTo(0, 0);
    dispatch({
      type: `xcxauth/GetAuthStatus`,
      callback: {
          success: (data) => {
              if (data.Code !== 0) {
                  router.replace({
                      pathname: `/${window.storeId}/wechat/miniapp`,
                  });
              } else {
                this.requestList();
              }
          }
      }
    });

  }
  requestList = () => {
    const { dispatch, form } = this.props;
    dispatch({
      type: 'xcxauth/GetTesterList',
      payload: {
        Type: this.state.Type,
        PageIndex: 1,
        PageSize: 10,
      },
      callback: {
        success: res => {
          if (res.Code == 0) {
            let { paginationProps } = this.state;
            let pagination = {
              ...paginationProps,
              total: Number(res.Data.Total),
            };
            this.setState({
              total: Number(res.Data.Total),
              paginationProps: { ...pagination },
              loading: false,
            });
          }
        },
      },
    });
  };
  onChange = data => {
    let { dispatch } = this.props;
    let { paginationProps } = this.state;
    let pagination = {
      ...paginationProps,
      ...data,
    };
    this.setState(
      {
        // current: data.current,
        // pageSize: data.pageSize,
        paginationProps: { ...pagination },
        loading: true,
      },
      () => {
        dispatch({
          type: 'xcxauth/GetTesterList',
          payload: {
            Type: this.state.Type,
            PageIndex: this.state.paginationProps.current,
            PageSize: this.state.paginationProps.pageSize,
          },
          callback: {
            success: res => {
              if (res.Code == 0) {
                let { paginationProps } = this.state;
                let pagination = {
                  ...paginationProps,
                  total: Number(res.Data.Total),
                };
                this.setState({
                  total: Number(res.Data.Total),
                  paginationProps: { ...pagination },
                  loading: false,
                });
              }
            },
          },
        });
      }
    );
  };
  onTabChange = id => {
    this.setState(
      {
        activeId: id,
      },
      () => {
        router.replace({
          pathname: `${id}`,
        });
      }
    );
  };
  removeBind = (id)=>{
    let { dispatch } = this.props;
    const that=this;
    confirm({
      title: '解绑后该用户无法再体验小程序，确定解除绑定？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: 'xcxauth/UnBindTester',
          payload: {
            WechartId: id,
          },
          callback: {
            success: res => {
              if(res.Code===0){
                message.success('解绑成功');
                that.requestList()
              }else{
                message.error('解绑失败：'+res.Msg);
              }
            }
          }
        });
      },
      onCancel() {
        console.log('Cancel');
      },
    });

  }
  newPage = () => {
    this.setState({
      visible: true,
    });
  };
  handleCancel = () => {
    this.props.form.setFieldsValue({'WechartId':''})
    this.setState({
      visible: false,
    });
  };
  show = type => {
    this.setState({
      showType: type,
    });
  };
  handleOk = () =>{
    let { form, dispatch } = this.props;
    form.validateFields((err, values) => {
      if(values.WechartId){
        dispatch({
          type: 'xcxauth/BindTester',
          payload: {
            WechartId: values.WechartId,
          },
          callback: {
            success: res => {
              if(res.Code===0){
                message.success('添加成功')
                this.handleCancel()
                this.requestList()
              }else{
                message.error('添加失败：'+res.Msg)
              }
            }
          }
        });
      }else{
        message.warn('请输入微信号')
      }

    })

  }
  render() {
    const { loadingTable,testerList, loadingBtn } = this.props;
    const { getFieldDecorator } = this.props.form;
    const { loading } = this.state;
    const DataList=testerList?testerList.DataList : [];
    const formItemLayout = {
      layout:"inline"
    };
    const columns = [
      {
        title: '微信号',
        dataIndex: 'WechartId',
        key: 'WechartId',
        width: '40%',
      },
      {
        title: '添加时间',
        dataIndex: 'BindTime',
        key: 'BindTime',
        width: '30%',
        align: 'left',
      },
      {
        title: '操作',
        dataIndex:'operation',
        key: 'operation',
        width: '30%',
        align: 'right',
        render: (text, data) => (
            <span
              className={`${styles.brandColor} ${styles.pointer}`}
              onClick={() => this.removeBind(data.WechartId)}
            >
              解绑
            </span>
        )
      },
    ];

    return (
      <Fragment>
          <Spin spinning={loading}>
          <Card bodyStyle={{minHeight:"320px"}}>
            <div style={{ marginBottom: 16 }}>
              <Button type="primary" onClick={this.newPage} style={{marginRight: 16}}>
                添加体验者
              </Button>
              <span>体验者能够在“小程序-版本管理”中预览小程序体验版</span>
              {/* <Button onClick={this.reload}>刷新</Button> */}
            </div>
            <Table
              columns={columns}
              loading={loadingTable}
              dataSource={DataList}
              rowKey="Id"
              onChange={this.onChange.bind(this)}
              pagination={this.state.paginationProps}
            />
          </Card>
          </Spin>
        <Modal
          title="添加体验者"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          width={720}
          className={styles.Modal}
          okButtonProps={{loading:loadingBtn}}
        >
          <div style={{ overflowY: 'auto', overflowX: 'hidden', maxHeight: '600px' }}>
          <Form {...formItemLayout}>
          <Form.Item
            label="微信号"
            help="输入微信号，微信号在“微信-我”页面最上方可以找到"
          >
            {getFieldDecorator('WechartId', {
            rules: [{
              required: true,
            }],
          })(
            <Input placeholder="请输入微信号" />
          )}

          </Form.Item>
          </Form>
          </div>
        </Modal>
      </Fragment>
    );
  }
}

export default connect(({ micropage, global, loading, xcxauth }) => ({
  micropage,
  wxaUrl:micropage.wxaUrl,
  microPageList: micropage.microPageList,
  testerList: xcxauth.testerList,
  loadingTable: loading.effects['xcxauth/GetTesterList'],
  loadingBtn: loading.effects['xcxauth/BindTester'],
}))(Pagination);
